package com.qhhc.controller;

import com.qhhc.entity.CarPhoto;
import com.qhhc.service.CarPhotoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.io.File;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/car-photos")
public class CarPhotoController {

    @Autowired
    private CarPhotoService carPhotoService;
    
    // 使用绝对路径，指向项目根目录下的resources/jpg目录
//    private static final String UPLOAD_DIR = "G:\\carshop02\\carshop\\src\\main\\resources\\static\\jpg";
    
    // 更新URL前缀为云服务器地址
    private static final String CLOUD_SERVER_URL = "http://101.34.246.109:9898";
    private static final String UPLOAD_API_URL = CLOUD_SERVER_URL + "/upload/api";
    private static final String IMAGE_URL_PREFIX = CLOUD_SERVER_URL + "/images/name/";
    
    // 创建RestTemplate实例用于HTTP请求
    private RestTemplate restTemplate;
    
    // 创建线程池
    private ExecutorService uploadExecutor;
    
    // 初始化线程池和RestTemplate
    @PostConstruct
    public void init() {
        // 创建一个固定大小的线程池，线程数量为CPU核心数的2倍
        int processors = Runtime.getRuntime().availableProcessors();
        uploadExecutor = Executors.newFixedThreadPool(processors * 2);
        System.out.println("图片上传线程池已初始化，线程数: " + (processors * 2));
        
        // 初始化RestTemplate
        restTemplate = new RestTemplate();
    }
    
    // 关闭线程池
    @PreDestroy
    public void destroy() {
        if (uploadExecutor != null) {
            uploadExecutor.shutdown();
            try {
                // 等待所有任务完成，最多等待30秒
                if (!uploadExecutor.awaitTermination(30, TimeUnit.SECONDS)) {
                    uploadExecutor.shutdownNow();
                }
            } catch (InterruptedException e) {
                uploadExecutor.shutdownNow();
                Thread.currentThread().interrupt();
            }
            System.out.println("图片上传线程池已关闭");
        }
    }

    @GetMapping("/car/{carId}")
    public ResponseEntity<List<CarPhoto>> getPhotosByCarId(@PathVariable Long carId) {
        return ResponseEntity.ok(carPhotoService.getPhotosByCarId(carId));
    }

    @PostMapping("/upload")
    public ResponseEntity<CarPhoto> uploadPhoto(
            @RequestParam("file") MultipartFile file,
            @RequestParam("carId") Long carId,
            @RequestParam(value = "isMain", defaultValue = "false") Boolean isMain) {
        try {
            // 上传文件到云服务器
            String fileName = uploadFileToCloud(file);
            
            if ("errorUpload".equals(fileName)) {
                return ResponseEntity.badRequest().build();
            }
            
            // 创建照片记录
            CarPhoto photo = new CarPhoto();
            photo.setCarId(carId);
            photo.setIsMain(isMain);
            // 设置照片URL为云服务器地址
            System.out.println("数据库中存储的url: " + fileName);
            photo.setPhotoUrl(IMAGE_URL_PREFIX + fileName);
            
            // 保存到数据库
            carPhotoService.save(photo);
            
            return ResponseEntity.ok(photo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }

    // 上传文件到云服务器的方法
    private String uploadFileToCloud(MultipartFile file) {
        try {
            // 创建HTTP头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            
            // 创建请求体
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", new HttpEntity<>(file.getResource()));
            
            // 创建HTTP实体
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
            
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(
                UPLOAD_API_URL,
                HttpMethod.POST,
                requestEntity,
                String.class
            );
            
            // 返回文件名
            if (response.getStatusCode().is2xxSuccessful()) {
                return response.getBody();
            } else {
                System.err.println("上传失败: " + response.getStatusCode());
                return "errorUpload";
            }
        } catch (Exception e) {
            System.err.println("上传过程中发生异常: " + e.getMessage());
            e.printStackTrace();
            return "errorUpload";
        }
    }

    @PutMapping("/{photoId}/main")
    public ResponseEntity<Boolean> setMainPhoto(
            @PathVariable Long photoId,
            @RequestParam Long carId) {
        return ResponseEntity.ok(carPhotoService.setMainPhoto(photoId, carId));
    }

    @DeleteMapping("/{photoId}")
    public ResponseEntity<Boolean> deletePhoto(@PathVariable Long photoId) {
        return ResponseEntity.ok(carPhotoService.deletePhoto(photoId));
    }

    @PutMapping("/{photoId}/sort")
    public ResponseEntity<Boolean> updatePhotoSort(
            @PathVariable Long photoId,
            @RequestParam Integer sortOrder) {
        return ResponseEntity.ok(carPhotoService.updatePhotoSort(photoId, sortOrder));
    }

    @PostMapping("/batch-upload")
    public ResponseEntity<?> batchUploadPhotos(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam("carId") Long carId,
            @RequestParam(value = "isMain", defaultValue = "false") Boolean isMain) {
        try {
            if (files.length == 0) {
                return ResponseEntity.badRequest().body("No files uploaded");
            }
            
            // 使用线程安全的集合
            List<CarPhoto> uploadedPhotos = Collections.synchronizedList(new ArrayList<>());
            
            // 创建所有异步任务，使用线程池
            List<CompletableFuture<Void>> futures = Arrays.stream(files)
                    .filter(file -> !file.isEmpty())
                    .map(file -> CompletableFuture.runAsync(() -> processFileCloud(file, carId, uploadedPhotos), uploadExecutor))
                    .collect(Collectors.toList());
            
            // 等待所有任务完成
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
            
            // 设置主图（取第一个非空结果）
            if (isMain && !uploadedPhotos.isEmpty()) {
                carPhotoService.setMainPhoto(uploadedPhotos.get(0).getPhotoId(), carId);
            }
            
            return ResponseEntity.ok(uploadedPhotos);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("Upload failed: " + e.getMessage());
        }
    }

    private void processFileCloud(MultipartFile file, Long carId, List<CarPhoto> uploadedPhotos) {
        try {
            // 上传文件到云服务器
            String fileName = uploadFileToCloud(file);
            
            if (!"errorUpload".equals(fileName)) {
                CarPhoto photo = new CarPhoto();
                photo.setCarId(carId);
                photo.setIsMain(false);
                photo.setPhotoUrl(IMAGE_URL_PREFIX + fileName);

                carPhotoService.save(photo);
                uploadedPhotos.add(photo); // 线程安全的添加操作
            } else {
                System.err.println("文件 " + file.getOriginalFilename() + " 上传失败");
            }
        } catch (Exception e) {
            throw new RuntimeException("文件处理失败: " + e.getMessage(), e);
        }
    }

    // 添加一个新方法来提供图片访问 - 这个方法可能不再需要，因为图片现在都在云端
    @GetMapping("/image/{fileName:.+}")
    public ResponseEntity<Resource> getImage(@PathVariable String fileName) {
        try {
            // 重定向到云服务器上的图片
            HttpHeaders headers = new HttpHeaders();
            headers.setLocation(java.net.URI.create(IMAGE_URL_PREFIX + fileName));
            return new ResponseEntity<>(headers, HttpStatus.FOUND);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
} 